package com.leng.logger.admin.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leng.common.constant.Constants;
import com.leng.common.constant.LoginErrorConstants;
import com.leng.common.utils.AddressUtils;
import com.leng.common.utils.IpUtils;
import com.leng.logger.admin.domain.AdminLogininfor;
import com.leng.logger.admin.mapper.AdminLogininforMapper;
import com.leng.logger.admin.service.IAdminLogininforService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class AdminLogininforServiceImpl extends ServiceImpl<AdminLogininforMapper, AdminLogininfor> implements IAdminLogininforService {

    /**
     * 插入登录日志
     * @param maps
     */
    @Override
    @Transactional
    public void addAdminLogininfor(HashMap<String, Object> maps) {
        StringBuilder s = new StringBuilder();
        s.append(getBlock(maps.get(LoginErrorConstants.LOGIN_IPADDR)));
        s.append(getBlock(maps.get(LoginErrorConstants.LOGIN_LOCATION)));
        s.append(getBlock(maps.get(LoginErrorConstants.USER_NAME)));
        s.append(getBlock(maps.get(LoginErrorConstants.LOGIN_STATUS)));
        s.append(getBlock(maps.get(LoginErrorConstants.LOGIN_MESSAGE)));
        // 打印信息到日志
        log.info(s.toString(), s);
        // 封装对象
        AdminLogininfor logininfor = new AdminLogininfor();
        logininfor.setUserName(maps.get(LoginErrorConstants.USER_NAME).toString());
        logininfor.setIpaddr(maps.get(LoginErrorConstants.LOGIN_IPADDR).toString());
        logininfor.setLoginLocation(maps.get(LoginErrorConstants.LOGIN_LOCATION).toString());
        logininfor.setBrowser(maps.get(LoginErrorConstants.LOGIN_BROWSER).toString());
        logininfor.setOs(maps.get(LoginErrorConstants.LOGIN_OS).toString());
        logininfor.setMsg(maps.get(LoginErrorConstants.LOGIN_MESSAGE).toString());
        logininfor.setLoginTime(new Date());
        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(getBlock(LoginErrorConstants.LOGIN_STATUS)) || Constants.LOGOUT.equals(getBlock(LoginErrorConstants.LOGIN_STATUS)))
        {
            logininfor.setStatus(Constants.SUCCESS);
        }
        else if (Constants.LOGIN_FAIL.equals(getBlock(LoginErrorConstants.LOGIN_STATUS)))
        {
            logininfor.setStatus(Constants.FAIL);
        }
        this.save(logininfor);
    }
    public static String getBlock(Object msg)
    {
        if (msg == null)
        {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }
}
